"""
    其实就是webserver_static2.py的类封装版

"""
import socket
import sys
from multiprocessing import Process


class WSGIServer(object):
    addressFamily = socket.AF_INET
    socketType = socket.SOCK_STREAM
    requestQueueSize = 5

    def __init__(self, server_address):
        self.listenSocket = socket.socket(self.addressFamily, self.socketType)
        self.listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.listenSocket.bind(server_address)
        self.listenSocket.listen(self.requestQueueSize)

    def serverForever():
        while True:
            self.clientSocket, client_address = self.listenSocket.accept()
            newClientProcess = Process(target=self.handleRequest)
            newClientProcess.start()
            self.clientSocket.close()

    def handleRequest():
        '用一个新的进程，为一个客户端进行服务'
        recvData = self.clientSocket.recv(2014)
        requestHeaderLines = recvData.splitlines()
        for line in requestHeaderLines:
            print(line)

        httpRequestMethodLine = requestHeaderLines[0]
        getFileName = re.match("[^/]+(/[^ ]*)", httpRequestMethodLine).group(1)
        print("file name is ===>%s" % getFileName)  # for test

        if getFileName == '/':
            getFileName = documentRoot + "/index.html"
        else:
            getFileName = documentRoot + getFileName

        print("file name is ===2>%s" % getFileName)  # for test

        try:
            f = open(getFileName)
        except IOError:
            responseHeaderLines = "HTTP/1.1 404 not found\r\n"
            responseHeaderLines += "\r\n"
            responseBody = "====sorry ,file not found===="
        else:
            responseHeaderLines = "HTTP/1.1 200 OK\r\n"
            responseHeaderLines += "\r\n"
            responseBody = f.read()
            f.close()
        finally:
            response = responseHeaderLines + responseBody
            self.clientSocket.send(response)
            self.clientSocket.close()


# 设定服务器的端口
serverAddr = (HOST, PORT) = '', 8888
# 设置服务器服务静态资源时的路径
documentRoot = './html'


def makeServer(serverAddr):
    server = WSGIServer(serverAddr)
    return server


def main():
    httpd = makeServer(serverAddr)
    print('web Server: Serving HTTP on port %d ...\n' % PORT)
    httpd.serveForever()

if __name__ == '__main__':
    main()
